package com.shkco.xbjcc.mq.listener;

import com.alibaba.fastjson.JSON;
import com.shkco.xbjcc.domain.CourseOrder;
import com.shkco.xbjcc.domain.CourseOrderItem;
import com.shkco.xbjcc.dto.PayDto;
import com.shkco.xbjcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = "tx-course-order-group")
public class CourseOrderTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            log.info("下单执行本地事务开始");
            if (o == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = JSON.parseObject(o.toString(), CourseOrder.class);
            List<CourseOrderItem> courseOrderItems = courseOrder.getCourseOrderItems();
            // 根据订单号查询是否已存在
            synchronized (courseOrder.getOrderNo()) {
                if (courseOrderService.selectByOrderNo(courseOrder.getOrderNo()) != null) {
                    log.info("订单已存在");
                    return RocketMQLocalTransactionState.ROLLBACK;
                }
                courseOrderService.saveCourseOrderAndItem(courseOrder);
            }
            log.info("下单执行本地事务结束");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("下单执行本地事务异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bytes = (byte[]) message.getPayload();
            String str = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(str, PayDto.class);
            if (payDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(payDto.getOrderNo());
            if (courseOrder == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
